package com.sondon.mayi.adapter;

import java.util.ArrayList;

import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EViewGroup;
import org.androidannotations.annotations.ViewById;
import org.apache.http.Header;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.loopj.android.http.TextHttpResponseHandler;
import com.sondon.mayi.activity.CommitActity_;
import com.sondon.mayi.configs.URLConfigs;
import com.sondon.mayi.entity.OrderInfo;
import com.sondon.mayi.entity.OrderInfo_Good;
import com.sondon.mayi.entity.RespondBaseEntity;
import com.sondon.mayi.events.OrderListUpdateEvent;
import com.sondon.mayi.fruit.R;
import com.sondon.mayi.util.AsyncHttpUtil;
import com.sondon.mayi.util.DensityUtil;
import com.sondon.mayi.util.GsonUtil;
import com.sondon.mayi.util.ImageLoaderUtil;
import com.sondon.mayi.util.LogUtil;
import com.sondon.mayi.util.PreferencesUtil;
import com.sondon.mayi.util.ToastUtils;

import de.greenrobot.event.EventBus;

/**
 * @Project : Fruit
 * @Package : com.sondon.mayi.adapter
 * @Class : OrderList_Item.java
 * @Company 广州讯动网络科技有限公司
 * @Author : 蔡文锋
 * @DateTime：2015-6-18 下午1:34:43
 * @Blog：http://blog.csdn.net/caiwenfeng_for_23
 * @Description : { 订单列表适配器 }
 */
@EViewGroup(R.layout.orderlist_item)
public class OrderList_Item extends LinearLayout {
	private Context context;
	
	@ViewById
	TextView orderlist_orderid;//订单号
	@ViewById
	TextView orderlist_orderstatue;//订单状态
	@ViewById
	TextView orderlist_item_price;//实付价钱
	@ViewById
	TextView orderlist_item_voucher;//现金券
	@ViewById
	TextView orderlist_item_count;//商品数
	@ViewById
	TextView orderlist_item_right;//右边的按钮（根据实际业务变换）
	@ViewById
	TextView orderlist_item_left;//删除订单按钮
	@ViewById
	LinearLayout orderlist_item_goodshow;//商品信息栏
	@ViewById
	TextView receiver;//收货人
	@ViewById
	TextView mobile;//手机号
	@ViewById
	TextView address;//收货地址
	@ViewById
	TextView receive_time;//收货时间
	@ViewById
	TextView order_content;//订单留言
	@ViewById
	TextView create_time;//订单生成时间
	
	
	private String Order_no;//订单ID
	private String phone;//送货员电话
	private int status_code;//订单状态

	//构造函数
	public OrderList_Item(Context context) {
		super(context);
		this.context=context;
	}
	
	//绑定数据
	public void bindData(OrderInfo orderinfo){
		//必须先清空LinearLayout里所有的view,
		//不然出现重复性问题,导致不能重用!
		orderlist_item_goodshow.removeAllViews();
		
		this.Order_no=orderinfo.getOrder_no();
		this.status_code=orderinfo.getStatus_code();
		this.phone=orderinfo.getPhone();
		
		orderlist_orderid.setText(orderinfo.getOrder_no());
		orderlist_orderstatue.setText(orderinfo.getStatus_name());
		orderlist_item_price.setText("￥ "+orderinfo.getPayable_amount());
		orderlist_item_voucher.setText("现金券："+orderinfo.getProp());
		orderlist_item_count.setText("共"+orderinfo.getGoods().size()+"件商品");
		
		receiver.setText(orderinfo.getAccept_name());
		mobile.setText(orderinfo.getMobile());
		
		String city=orderinfo.getCity_name();
		if("市辖区".equals(city)||"县".equals(city)){
			city="";
		}
		address.setText(orderinfo.getProvince_name()+city+orderinfo.getArea_name()+orderinfo.getAddress());
		receive_time.setText(orderinfo.getAccept_time());
		order_content.setText(orderinfo.getPostscript());
		create_time.setText(orderinfo.getCreate_time());
		
		//右边的按钮（根据实际业务变换）
		RightButtonInitView(this.status_code);
		//加载物品清单数据
		LoadGoodsList(orderinfo);
	}
	
	//点击事件
	@Click({R.id.orderlist_item_left,R.id.orderlist_item_right})
	public void onClick(View v){
		switch (v.getId()) {
		case R.id.orderlist_item_left://左边的按钮
			bussinessToDo(orderlist_item_left.getText().toString().trim());
			break;
		case R.id.orderlist_item_right://右边的按钮
			bussinessToDo(orderlist_item_right.getText().toString().trim());
			break;
		default:
			break;
		}
	}
	
	
	//加载物品清单数据
	@SuppressLint("InflateParams")
	public void LoadGoodsList(OrderInfo orderinfo){
		ArrayList<OrderInfo_Good> list=orderinfo.getGoods();
		if(orderinfo.getGoods().size()>0){
			for(int i=0;i<list.size();i++){
				View v=LayoutInflater.from(context).inflate(R.layout.order_confirm_item, null);
				
				ImageView order_confirm_item_img=(ImageView) v.findViewById(R.id.order_confirm_item_img);
				TextView order_confirm_item_name=(TextView) v.findViewById(R.id.order_confirm_item_name);
				TextView order_confirm_item_oneprice=(TextView) v.findViewById(R.id.order_confirm_item_oneprice);
				TextView order_confirm_item_num=(TextView) v.findViewById(R.id.order_confirm_item_num);
				
				order_confirm_item_name.setText(list.get(i).getName());
				order_confirm_item_oneprice.setText(" ￥"+orderinfo.getGoods().get(i).getGoods_price());
				order_confirm_item_num.setText("X "+list.get(i).getGoods_nums());
				ImageLoaderUtil.SetImgView(orderinfo.getGoods().get(i).getImg(), order_confirm_item_img);
				
				//向上间距2dp
				LayoutParams layoutParams=new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
				layoutParams.setMargins(0, DensityUtil.dip2px(context, 2), 0, 0);// 左上右下
				orderlist_item_goodshow.addView(v,layoutParams);
			}
		}
	}
	
	//点击按钮,处理业务逻辑
	public void bussinessToDo(String butt_txt){
		if("取消订单".equals(butt_txt)){
			CancleOrder();
		}else if("去支付".equals(butt_txt)){
			ToastUtils.show(context, "去支付");
		}else if("联系送货员".equals(butt_txt)){
			CannectSender();
		}else if("删除订单".equals(butt_txt)){
			DelOrder();
		}else if("评论订单".equals(butt_txt)){
			CommentOrder();
		}else if("已评论".equals(butt_txt)){
			//不做任何处理
		}
	}
	/**
	 * 右边的按钮（根据实际业务变换）
	 * 订单状态
	 * status_name="未付款"; status_code=0;
	 * status_name="待确定"; status_code=1; 
	 * status_name="配送中"; status_code=2;
	 * status_name="已取消"; status_code=3; 
	 * status_name="已完成"; status_code=4;
	 * status_name="已退货"; status_code=5;
	 */
	public void RightButtonInitView(int status_code){
		//恢复默认状态
		orderlist_item_right.setEnabled(true);
		orderlist_item_left.setEnabled(true);
		orderlist_item_left.setVisibility(View.VISIBLE);
		
		switch (this.status_code) {
		case 0://未付款
			orderlist_item_left.setText("取消订单");
			orderlist_item_right.setText("去支付");
			break;
		case 1://待确定
			orderlist_item_left.setVisibility(View.GONE);
			orderlist_item_right.setText("取消订单");
			break;
		case 2://配送中
			orderlist_item_left.setText("取消订单");
			orderlist_item_right.setText("联系送货员");
			break;
		case 3://已取消
			orderlist_item_left.setVisibility(View.GONE);
			orderlist_item_right.setText("删除订单");
			break;
		case 4://已完成
			orderlist_item_left.setText("删除订单");
			orderlist_item_right.setText("评论订单");
			break;
		case 5://已退货
			orderlist_item_right.setText("删除订单");
			orderlist_item_left.setVisibility(View.GONE);
			break;
		case 6://已评论
			orderlist_item_left.setText("删除订单");
			orderlist_item_right.setText("已评论");
			orderlist_item_right.setEnabled(false);
			break;
		default:
			break;
		}
	}
	
	
	//评价订单
	public void CommentOrder(){
//		ToastUtils.show(context, "评价订单");
		Intent intent=new Intent(this.context,CommitActity_.class);
		intent.putExtra("Order_no", this.Order_no);
		this.context.startActivity(intent);
	}
	
	
	//联系送货员
	public void CannectSender(){
		//用intent启动拨打电话  
        Intent intent = new Intent(Intent.ACTION_CALL,Uri.parse("tel:"+this.phone));  
        this.context.startActivity(intent); 
	}
	
	
	//取消订单
	public void CancleOrder(){
		AsyncHttpUtil.get(URLConfigs.CancleOrder_ukey
						+ PreferencesUtil.getStringValue("Ukey") + "&id="
						+ this.Order_no, null, new TextHttpResponseHandler() {

					@Override
					public void onSuccess(int status, Header[] arg1, String json) {
						LogUtil.e("OrderList_Item", "cancleorder json :" + json);
						if (200 == status) {
							RespondBaseEntity entity=GsonUtil.GetFromJson(json, RespondBaseEntity.class);
							if(entity.isStatus()){
								EventBus.getDefault().post(new OrderListUpdateEvent());
							}else{
								ToastUtils.show(getContext(),entity.getMsg());
							}
						}
					}

					@Override
					public void onFailure(int arg0, Header[] arg1, String arg2,
							Throwable arg3) {
						ToastUtils.show(getContext(),R.string.network_unavailable);
					}
				});
	}
	
	
	//删除订单
	public void DelOrder(){
		AsyncHttpUtil.get(URLConfigs.DelOrder_ukey
						+ PreferencesUtil.getStringValue("Ukey") + "&id="
						+ this.Order_no, null, new TextHttpResponseHandler() {

					@Override
					public void onSuccess(int status, Header[] arg1, String json) {
						LogUtil.e("OrderList_Item", "delorder json :" + json);
						if (200 == status) {
							RespondBaseEntity entity=GsonUtil.GetFromJson(json, RespondBaseEntity.class);
							if(entity.isStatus()){
								EventBus.getDefault().post(new OrderListUpdateEvent());
							}else{
								ToastUtils.show(getContext(),entity.getMsg());
							}
						}
					}

					@Override
					public void onFailure(int arg0, Header[] arg1, String arg2,
							Throwable arg3) {
						ToastUtils.show(getContext(),R.string.network_unavailable);
					}
				});
	}
}
